const Article = require('../../models/article')

module.exports = (req, res) => {
  var formData = {}
  // console.log(req.body);
  formData._id = req.body._id
  formData.commentItems = JSON.parse(req.body.commentItems)
  // console.log(formData);
  /* 
    1、先从数据库把文章找出来
    2、然后在将新的commentItems插入到commentArea数组里面
    3、最后在将更新完的commentArea覆盖到原本的commentArea
  */
  Article.findById({ _id: formData._id }, (err, articleDoc) => {
    // console.log(articleDoc)

    articleDoc.commentArea.push(formData.commentItems)
    articleDoc.last_modified_time = new Date
    // console.log(articleDoc.commentArea)

    Article.findByIdAndUpdate({
      _id: formData._id
    }, {
      commentArea: articleDoc.commentArea,
      last_modified_time:articleDoc.last_modified_time
    }, (err) => {
      // 重新查询新数据
      Article.findById({
        _id: formData._id
      }, (err, newArticleDoc) => {
        if (err) {
          return res.status(500).json({
            err_code: 500,
            message: err.message
          })
        }
        // console.log(newArticleDoc)
        res.status(200).json({
          err_code: 0,
          data: newArticleDoc,
          message: 'comment success'
        })
      })

    })
  })
}